import actory, random, math

class Factory(object):
    "a collection of machines"
    def __init__(self, printflag = True):
        global PRINT_FLAG
        PRINT_FLAG = printflag
        self.factory = []
        self.size = 0
        self.spots = []
    def add_machine(self, machine):
        "add a machine to the factory"
        self.factory.append(machine)
        self.size = self.size + 1
        for i in range(machine.priority):
            self.spots.append(self.size-1)
    def shuffle(self):
        "randomizes the order of machines in the factory"
        random.shuffle(self.factory)
    def sort(self, order=1):
        "sort the order of the machines via priority"
        "order=1 descending priority (higher priority in front)"
        "order=0 ascending priority (lower priority in front)"
        self.factory.sort(key=lambda sorter: sorter.priority, reverse=order)
        "display result"
        self.__repr__()
    def __repr__(self):
        for i in range(self.size):
            if PRINT_FLAG:
                print "Machine " + str(i) + ": priority = " + str(self.factory[i].priority)
    def run(self, universe, steps):      
        "runs a random machine, firing one action only per machine"
        for i in range(1,steps):
            m = self.spots[random.randint(0,len(self.spots)-1)]
            universe = self.factory[m].run_one(universe)
            if not self.factory[m].here.goOn1("", universe):
                break
                
        
